package model;

import handler.APIAlbumCover;
import handler.APIMediaTag;
import handler.FileFilter;
import handler.Utilities;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;

import org.xml.sax.SAXException;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

/**
 * MusicDB allow to have some information on database about music
 * @author Jean
 *
 */

public class MusicDB {
	
	//pathname of musics	
	private static final int VERSION_BDD = 1;
	private static final String NOM_BDD = "music.db";
	// Music COL
	private static final String TABLE_MUSIC = "music";
	private static final String COL_ID_MUSIC = "id";
	private static final String COL_FILENAME = "filename";
	private static final String COL_PATHNAME = "pathname";
	private static final String COL_TITLE = "title";
	private static final String COL_TRACKNUMBER = "trackNumber";
	private static final String COL_NBPLAY = "nbPlay";
	private static final String COL_ISLIKE = "isLike";
	private static final String COL_IDARTIST = "idArtist";
	private static final String COL_IDALBUM = "idAlbum";
	private static final String COL_IDGENRE = "idGenre";
	private static final String COL_IDPLAYLIST = "idPlaylist";
	// Artist COL
	private static final String TABLE_ARTIST = "artist";
	private static final String COL_ID_ARTIST = "id";
	private static final String COL_NAMEARTIST = "name";
	// Album COL
	private static final String TABLE_ALBUM = "album";
	private static final String COL_ID_ALBUM = "id";
	private static final String COL_NAMEALBUM = "name";
	private static final String COL_ALBUMCOVER = "albumCover";
	// Playlist COL
	private static final String TABLE_PLAYLIST = "playlist";
	private static final String COL_ID_PLAYLIST = "id";
	private static final String COL_NAMEPLAYLIST = "name";
	// Genre COL
	private static final String TABLE_GENRE = "genre";
	private static final String COL_ID_GENRE = "id";
	private static final String COL_NAMEGENRE = "name";
	
	private static final String GENRES_PATH = "assets/genres.txt";
	
	private SQLiteDatabase db;
	private MySQLite myDbLite;
	
	private ArrayList<HashMap<String, String>> list;
	
	private Utilities util = new Utilities();
	
	/**
	 * Constructor of MusicDB
	 * @param context
	 */
	public MusicDB(Context context){
		// Create the DB SQLite
		myDbLite = new MySQLite(context, NOM_BDD, null, VERSION_BDD);
	}
	
	public MusicDB(Context context, ArrayList<HashMap<String, String>> l) {
		// Create the DB SQLite
		myDbLite = new MySQLite(context, NOM_BDD, null, VERSION_BDD);
		list = l;
	}
	
	/**
	 * Open a connection
	 */
	public void open(){
		// Open our DB
		db = myDbLite.getWritableDatabase();
	}
	
	/**
	 * Close a connection
	 */
	public void close(){
		// Close our DB
		db.close();
	}
	
	/**
	 * Get the SQLiteDatabase object
	 * @return db
	 */
	public SQLiteDatabase getBDD(){
		// return db object
		return db;
	}
	
	/**
	 * Get the MySQLite object
	 * @return myDbLite
	 */
	public MySQLite getMyDb(){
		// return db object
		return myDbLite;
	}
	
	/*
	 * Here we have the add methods, allowing to add music, artist, album,...
	 */
	/**
	 * Add a music in the database
	 * @param m	Music
	 * @return the long id of the newly row inserted in the database, or -1 if an error occurred
	 */
	public long addMusic(Music m) {
		ContentValues values = new ContentValues();
		values.put(COL_FILENAME, m.getFileName());
		values.put(COL_PATHNAME, m.getPathName());
		values.put(COL_TITLE, m.getTitle());
		values.put(COL_TRACKNUMBER, m.getTrackNumber());
		values.put(COL_NBPLAY, m.getNbPlay());
		values.put(COL_ISLIKE, m.isLike());
		values.put(COL_IDARTIST, m.getIdArtist());
		values.put(COL_IDALBUM, m.getIdAlbum());
		values.put(COL_IDGENRE, m.getIdGenre());
		values.put(COL_IDPLAYLIST, m.getIdPlaylist());
		return db.insert(TABLE_MUSIC, null, values);
	}
	
	/**
	 * Add an artist in the database
	 * @param s	Name of the new Artist
	 * @return the long id of the newly row inserted in the database, or -1 if an error occurred
	 */
	public long addArtist(String s) { // Add artist or return the id of existing artist
		int i = issetArtist(s);
		if(i == -1) {
			ContentValues values = new ContentValues();
			values.put(COL_NAMEARTIST, s);
			return db.insert(TABLE_ARTIST, null, values);
		} else return i;
	}
	
	/**
	 * Add an album in the database
	 * @param s	the name of the album
	 * @param albumCover
	 * @param idArtist
	 * @return the long id of the newly row inserted in the database, or -1 if an error occurred
	 */
	public long addAlbum(String s, byte[] albumCover, int idArtist) {
		int i = issetAlbum(s);
		if(i == -1) {
			ContentValues values = new ContentValues();
			values.put(COL_NAMEALBUM, s);
			values.put(COL_ALBUMCOVER, albumCover);
			values.put(COL_IDARTIST, idArtist);
			return db.insert(TABLE_ALBUM, null, values);
		} else return i;
	}
	
	/**
	 * Add a playlist in the database
	 * @param s The name of the playlist
	 * @return the long id of the newly row inserted in the database, or -1 if an error occurred
	 */
	public long addPlaylist(String s) {
		int i = issetPlaylist(s);
		if(i == -1) {
			ContentValues values = new ContentValues();
			values.put(COL_NAMEPLAYLIST, s);
			return db.insert(TABLE_PLAYLIST, null, values);
		} else return i;
	}
	
	/**
	 * Add a genre in the database
	 * @param g	Genre
	 * @return the long id of the newly row inserted in the database, or -1 if an error occurred
	 */
	public long addGenre(Genre g) {
		int i = issetGenre(g.getId());
		if(i == -1) {
			ContentValues values = new ContentValues();
			values.put(COL_ID_GENRE, g.getId());
			values.put(COL_NAMEGENRE, g.getName());
			return db.insert(TABLE_GENRE, null, values);
		} else return i;
	}
	
	/*
	 * Here we have the delete methods, allowing to delete music, artist, album,...
	 */
	/**
	 * Delete a music from database
	 * @param id
	 * @return the number of rows affected if a whereClause is passed in, 0 otherwise.
	 */
	public int deleteMusic(int id) {
		return db.delete(TABLE_MUSIC, COL_ID_MUSIC + "=" + id, null);
	}
	
	/**
	 * Delete an artist from database
	 * @param id
	 * @return the number of rows affected if a whereClause is passed in, 0 otherwise.
	 */
	public int deleteArtist(int id) {
		return db.delete(TABLE_ARTIST, COL_ID_ARTIST + "=" + id, null);
	}
	
	/**
	 * Delete an album from database
	 * @param id
	 * @return the number of rows affected if a whereClause is passed in, 0 otherwise.
	 */
	public int deleteAlbum(int id) {
		return db.delete(TABLE_ALBUM, COL_ID_ALBUM + "=" + id, null);
	}
	
	/**
	 * Delete a genre from database
	 * @param id
	 * @return the number of rows affected if a whereClause is passed in, 0 otherwise.
	 */
	public int deleteGenre(int id) {
		return db.delete(TABLE_GENRE, COL_ID_GENRE + "=" + id, null);
	}
	
	/**
	 * Delete a playlist from database
	 * @param id
	 * @return the number of rows affected if a whereClause is passed in, 0 otherwise.
	 */
	public int deletePlaylist(int id) {
		return db.delete(TABLE_PLAYLIST, COL_ID_PLAYLIST + "=" + id, null);
	}
	
	/*
	 * Here we have the get methods, allowing to get music, artist, album,...
	 */
	
	/**
	 * Get all music from the database
	 * @return A Cursor object, which is positioned before the first entry
	 */
	public Cursor getAllMusic() {
		return db.query(TABLE_MUSIC, null, null, null, null, null, null);
	}
	
	/**
	 * Get musics by an artist
	 * @param a
	 * @return A Cursor object, which is positioned before the first entry
	 */
	public Cursor getMusicByArtist(Artist a) {
		return db.query(TABLE_MUSIC, null, COL_IDARTIST + "=" + a.getId(), null, null, null, null);
	}
	
	/**
	 * Get musics by an album
	 * @param a
	 * @return A Cursor object, which is positioned before the first entry
	 */
	public Cursor getMusicByAlbum(Album a) {
		return db.query(TABLE_MUSIC, null, COL_IDALBUM + "=" + a.getId(), null, null, null, null);
	}
	
	/**
	 * Get musics by a playlist
	 * @param p
	 * @return A Cursor object, which is positioned before the first entry
	 */
	public Cursor getMusicByPlaylist(Playlist p) {
		return db.query(TABLE_MUSIC, null, COL_IDPLAYLIST + "=" + p.getId(), null, null, null, null);
	}
	
	/**
	 * Get musics by a genre
	 * @param g
	 * @return A Cursor object, which is positioned before the first entry
	 */
	public Cursor getMusicByGenre(Genre g) {
		return db.query(TABLE_MUSIC, null, COL_IDGENRE + "=" + g.getId(), null, null, null, null);
	}
	
	/**
	 * Get all artist
	 * @return A Cursor object, which is positioned before the first entry
	 */
	public Cursor getAllArtist() {
		return db.query(TABLE_ARTIST, null, null, null, null, null, null);
	}
	
	/**
	 * Get an artist
	 * @param id
	 * @return A Cursor object, which is positioned before the first entry
	 */
	public Cursor getArtist(int id) {
		return db.query(TABLE_ARTIST, null, COL_ID_ARTIST + "=" + id, null, null, null, null);
	}
	
	/**
	 * Get all album
	 * @return A Cursor object, which is positioned before the first entry
	 */
	public Cursor getAllAlbum() {
		return db.query(TABLE_ALBUM, null, null, null, null, null, null);
	}
	
	/**
	 * Get an album
	 * @param id
	 * @return A Cursor object, which is positioned before the first entry
	 */
	public Cursor getAlbum(int id) {
		return db.query(TABLE_ALBUM, null, COL_ID_ALBUM + "=" + id, null, null, null, null);
	}
	
	/**
	 * Get albums by an artist
	 * @param a Artist
	 * @return A Cursor object, which is positioned before the first entry
	 */
	public Cursor getAlbumByArtist(Artist a) {
		return db.query(TABLE_ALBUM, null, COL_IDARTIST + "=" + a.getId(), null, null, null, null);
	}
	
	/**
	 * Get all playlist
	 * @return A Cursor object, which is positioned before the first entry
	 */
	public Cursor getAllPlaylist() {
		return db.query(TABLE_PLAYLIST, null, null, null, null, null, null);
	}
	
	/**
	 * Get a playlist
	 * @param id
	 * @return A Cursor object, which is positioned before the first entry
	 */
	public Cursor getPlaylist(int id) {
		return db.query(TABLE_PLAYLIST, null, COL_ID_PLAYLIST + "=" + id, null, null, null, null);
	}
	
	/**
	 * Get all genre
	 * @return A Cursor object, which is positioned before the first entry
	 */
	public Cursor getAllGenre() {
		return db.query(TABLE_GENRE, null, null, null, null, null, null);
	}
	
	/**
	 * Get music with the id into an array of Int
	 * @param id int[]
	 * @return A Cursor object, which is positioned before the first entry
	 */
	public Cursor getMusicByArrayId(int[] id) {
		StringBuilder req = new StringBuilder();
		for(int i=0;i<id.length;i++) {
			req.append(COL_ID_MUSIC + "=" + id[i]);
			if(i<(id.length-1)) req.append(" OR ");
		}
		return db.query(TABLE_MUSIC, null, req.toString(), null, null, null, null);
	}
	
	/*
	 * Method allowing to have Object with Cursor
	 */
	
	/**
	 * Have an Array of Music from a Cursor
	 * @param c
	 * @return ArrayList<Music>
	 */
	public ArrayList<Music> cursorToMusic(Cursor c) {
		ArrayList<Music> list = new ArrayList<Music>();
		boolean isNotEmpty = c.moveToFirst();
		while(isNotEmpty) {
			Music m = new Music();
			m.setId(c.getInt(c.getColumnIndexOrThrow(COL_ID_MUSIC)));
			m.setFileName(c.getString(c.getColumnIndexOrThrow(COL_FILENAME)));
			m.setPathName(c.getString(c.getColumnIndexOrThrow(COL_PATHNAME)));
			m.setTitle(c.getString(c.getColumnIndexOrThrow(COL_TITLE)));
			m.setTrackNumber(c.getString(c.getColumnIndexOrThrow(COL_TRACKNUMBER)));
			m.setNbPlay(c.getInt(c.getColumnIndexOrThrow(COL_NBPLAY)));
			m.setLike(c.getInt(c.getColumnIndexOrThrow(COL_ISLIKE))>0);
			m.setIdArtist(c.getInt(c.getColumnIndexOrThrow(COL_IDARTIST)));
			m.setIdAlbum(c.getInt(c.getColumnIndexOrThrow(COL_IDALBUM)));
			m.setIdPlaylist(c.getInt(c.getColumnIndexOrThrow(COL_IDPLAYLIST)));
			m.setIdGenre(c.getInt(c.getColumnIndexOrThrow(COL_IDGENRE)));
			list.add(m);
			isNotEmpty = c.moveToNext();
		}
		list.trimToSize();
		return list;
	}
	
	/**
	 * Have an Array of Artist from a Cursor
	 * @param c
	 * @return ArrayList<Artist>
	 */
	public ArrayList<Artist> cursorToArtist(Cursor c) {
		ArrayList<Artist> list = new ArrayList<Artist>();
		boolean isNotEmpty = c.moveToFirst();
		while(isNotEmpty) {
			Artist a = new Artist();
			a.setId(c.getInt(c.getColumnIndexOrThrow(COL_ID_ARTIST)));
			a.setName(c.getString(c.getColumnIndexOrThrow(COL_NAMEARTIST)));
			isNotEmpty = c.moveToNext();
			list.add(a);
		}
		list.trimToSize();
		return list;
	}
	
	/**
	 * Have an Array of Album from a Cursor
	 * @param c
	 * @return ArrayList<Album>
	 */
	public ArrayList<Album> cursorToAlbum(Cursor c) {
		ArrayList<Album> list = new ArrayList<Album>();
		boolean isNotEmpty = c.moveToFirst();
		while(isNotEmpty) {
			Album a = new Album();
			a.setId(c.getInt(c.getColumnIndexOrThrow(COL_ID_ALBUM)));
			a.setName(c.getString(c.getColumnIndexOrThrow(COL_NAMEALBUM)));
			a.setAlbumCover(c.getBlob(c.getColumnIndexOrThrow(COL_ALBUMCOVER)));
			a.setIdArtist(c.getInt(c.getColumnIndexOrThrow(COL_IDARTIST)));
			isNotEmpty = c.moveToNext();
			list.add(a);
		}
		list.trimToSize();
		return list;
	}
	
	/**
	 * Have an Array of Genre from a Cursor
	 * @param c
	 * @return ArrayList<Genre>
	 */
	public ArrayList<Genre> cursorToGenre(Cursor c) {
		ArrayList<Genre> list = new ArrayList<Genre>();
		boolean isNotEmpty = c.moveToFirst();
		while(isNotEmpty) {
			Genre g = new Genre();
			g.setId(c.getInt(c.getColumnIndexOrThrow(COL_ID_GENRE)));
			g.setName(c.getString(c.getColumnIndexOrThrow(COL_NAMEGENRE)));
			isNotEmpty = c.moveToNext();
			list.add(g);
		}
		list.trimToSize();
		return list;
	}
	
	/**
	 * Have an Array of Playlist from a Cursor
	 * @param c
	 * @return ArrayList<Playlist>
	 */
	public ArrayList<Playlist> cursorToPlaylist(Cursor c) {
		ArrayList<Playlist> list = new ArrayList<Playlist>();
		boolean isNotEmpty = c.moveToFirst();
		while(isNotEmpty) {
			Playlist p = new Playlist();
			p.setId(c.getInt(c.getColumnIndexOrThrow(COL_ID_PLAYLIST)));
			p.setName(c.getString(c.getColumnIndexOrThrow(COL_NAMEPLAYLIST)));
			isNotEmpty = c.moveToNext();
			list.add(p);
		}
		list.trimToSize();
		return list;
	}
	
	/*
	 * Here we have isset methods
	 */
	
	/**
	 * Verify if the artist exist
	 * @param s
	 * @return the id of the artist or -1 else
	 */
	public int issetArtist(String s) {
		Cursor c = db.query(TABLE_ARTIST, new String[] {COL_ID_ARTIST}, COL_NAMEARTIST + " LIKE '" + s.replace("'", "''") + "'", null, null, null, null, null);
		if(c.moveToFirst()) {
			return c.getInt(c.getColumnIndexOrThrow(COL_ID_ARTIST));
		} else return -1;
	}
	
	/**
	 * Verify if the album exist
	 * @param s
	 * @return the id of the album or -1 else
	 */
	public int issetAlbum(String s) {
		Cursor c = db.query(TABLE_ALBUM, new String[] {COL_ID_ALBUM}, COL_NAMEALBUM + " LIKE '" + s.replace("'", "''") + "'", null, null, null, null, null);
		if(c.moveToFirst()) {
			return c.getInt(c.getColumnIndexOrThrow(COL_ID_ALBUM));
		} else return -1;
	}
	
	/**
	 * Verify if the genre exist
	 * @param id
	 * @return the id of the genre or -1 else
	 */
	public int issetGenre(int id) {
		Cursor c = db.query(TABLE_GENRE, new String[] {COL_ID_GENRE}, COL_ID_GENRE + " = " + id, null, null, null, null, null);
		if(c.moveToFirst()) {
			return c.getInt(c.getColumnIndexOrThrow(COL_ID_GENRE));
		} else return -1;
	}
	
	/**
	 * Verify if the genre exist
	 * @param s
	 * @return the id of the genre or -1 else
	 */
	public int issetGenre(String s) {
		Cursor c = db.query(TABLE_GENRE, new String[] {COL_ID_GENRE}, COL_NAMEGENRE + " LIKE '" + s.replace("'", "''") + "'", null, null, null, null, null);
		if(c.moveToFirst()) {
			return c.getInt(c.getColumnIndexOrThrow(COL_ID_GENRE));
		} else return -1;
	}
	
	/**
	 * Verify if the playlist exist
	 * @param s
	 * @return the id of the playlist or -1 else
	 */
	public int issetPlaylist(String s) {
		Cursor c = db.query(TABLE_PLAYLIST, new String[] {COL_ID_PLAYLIST}, COL_NAMEPLAYLIST + " LIKE '" + s.replace("'", "''") + "'", null, null, null, null, null);
		if(c.moveToFirst()) {
			return c.getInt(c.getColumnIndexOrThrow(COL_ID_PLAYLIST));
		} else return -1;
	}
	
	
	/*
	 * Here we have the update methods, allowing to update music, artist, album,...
	 */
	
	/**
	 * Update a music
	 * @param m
	 * @return the number of rows affected
	 */
	public int updateMusicComparedWithSD(Music m) {
		ContentValues values = new ContentValues();
		values.put(COL_TITLE, m.getTitle());
		values.put(COL_TRACKNUMBER, m.getTrackNumber());
		values.put(COL_IDARTIST, m.getIdArtist());
		values.put(COL_IDALBUM, m.getIdAlbum());
		values.put(COL_IDGENRE, m.getIdGenre());
		return db.update(TABLE_MUSIC, values, COL_ID_MUSIC+"="+m.getId(), null);
	}
	
	/**
	 * Update the like of a music
	 * @param idMusic
	 * @param value
	 * @return the number of rows affected
	 */
	public int updateLike(int idMusic, boolean value) {
		ContentValues values = new ContentValues();
		values.put(COL_ISLIKE, value);
		return db.update(TABLE_MUSIC, values, COL_ID_MUSIC+"="+idMusic, null);
	}
	
	public int updateAlbum(Album a){
		ContentValues values = new ContentValues();
		//values.put(COL_ID_ALBUM, a.getId());
		values.put(COL_ALBUMCOVER, a.getAlbumCover());
		//values.put(COL_NAMEALBUM, a.getName());
		return db.update(TABLE_ALBUM, values, COL_ID_ALBUM+ "=" + a.getId() , null);
	}
	
	
	/**
	 * Update the nbPlay of a music
	 * @param idMusic
	 * @param nbPlay
	 * @return
	 */
	public int updateNbplay(int idMusic, int nbPlay) {
		ContentValues values = new ContentValues();
		values.put(COL_NBPLAY, nbPlay+1);
		return db.update(TABLE_MUSIC, values, COL_ID_MUSIC+"="+idMusic, null);
	}
	
	/*
	 * updateDb() allow to update the db with the current mp3 files on SDCard
	 */
	
	/**
	 * Method allowing to update the database. Insert, update or delete in comparating with the sd card.
	 */
	public void updateDb() {
		Cursor c = db.query(TABLE_MUSIC, new String[] {	COL_ID_MUSIC,
														COL_FILENAME,
														COL_PATHNAME,
														COL_TITLE,
														COL_TRACKNUMBER,
														COL_IDARTIST,
														COL_IDALBUM,
														COL_IDGENRE}, null, null, null, null, null);
		
		File genres = new File(GENRES_PATH); // We retrieve the file genres.txt, and fill the DB
		
		//Read text from file
		try {
		    BufferedReader br = new BufferedReader(new FileReader(genres));
		    String line;
		    while ((line = br.readLine()) != null) {
		        String[] tab = line.split(".");
		        Genre g = new Genre(Integer.parseInt(tab[0]),tab[1]);
		        if(issetGenre(g.getId()) == -1) { // Doesn't exist !
		        	addGenre(g);
		        }
		    }
		}
		catch (IOException e) {
		    //You'll need to add proper error handling here
		}
		
		/*
		 * We will do : for(SD){for(TABLE)} for add or update the table on the database
		 * then : for(TABLE){for(SD)} for remove the useless rows 
		 */
		boolean tableIsEmpty = c.moveToFirst();
		boolean isToAdd = true;
		boolean isToDelete = true;
		int i;
		
		if (list.size() > 0) {
			// ADD OR UPDATE TABLE
			for(i=0;i<list.size();i++) { // SD
			
				while(tableIsEmpty && isToAdd) { // TABLE MUSIC : On sort que si on trouve une �galit� ou si la table est compl�tement parcouru !
					if(list.get(i).get("pathname").equals(c.getString(c.getColumnIndexOrThrow(COL_PATHNAME)))) {
						isToAdd = false;
					}
					else tableIsEmpty = c.moveToNext();
				}
				// Set MediaMetadataRetriever
				APIMediaTag mmr = new APIMediaTag(list.get(i).get("pathname"));
				// Prepare Music Object
				Music m = new Music();
				
				String title = mmr.getTitle();
				String artist = mmr.getArtist();
				String album = mmr.getAlbum();
				String genre = mmr.getGenre();

				if(title == null) title = "Unknown title";
				else if(title.equals("")) title = "Unknown title";
				if(artist == null) artist = "Unknown artist";
				else if(artist.equals("")) artist = "Unknown artist";
				if(album == null) album = "Unknown album";
				else if(album.equals("")) album = "Unknown album";
				if(genre == null) genre = "-1";
				else if(genre.equals("")) genre = "-1";
				// Set Music Object
				m.setTitle(title);
				m.setTrackNumber(mmr.getTrackNumber());
				m.setFileName(list.get(i).get("filename"));
				m.setPathName(list.get(i).get("pathname"));
				m.setIdArtist((int) addArtist(artist));
				m.setIdAlbum((int) addAlbum(album, mmr.getImage(), m.getIdArtist()));
				// Verify if genre is a number or a string before save it...
				boolean isANumber = true;
				try {
					Integer.parseInt(genre);
				} catch(NumberFormatException e) { // Not a number !
					isANumber = false;
				}
				
				int idGenre;
				if(isANumber) idGenre = issetGenre(Integer.parseInt(genre));
				else idGenre = issetGenre(genre);
				
				m.setIdGenre(idGenre);
				if(isToAdd) {
					//Insert...
					addMusic(m);
					// ajouter exceptions...
				} else {
					//Update...
					// Tout mettre � jour sauf pathname et filename
					m.setId(c.getInt(c.getColumnIndex(COL_ID_MUSIC)));
					updateMusicComparedWithSD(m);
				}
				isToAdd = true;
			}
			// DELETE USELESS ROW IN TABLE 
			tableIsEmpty = c.moveToFirst();
			while(tableIsEmpty) { // TABLE MUSIC
				for(i=0;i<list.size();i++) {
					if(list.get(i).get("pathname").equals(c.getString(c.getColumnIndexOrThrow(COL_PATHNAME)))) isToDelete = false;
				}
				if(isToDelete) {
					//Delete...
					deleteMusic(c.getInt(c.getColumnIndexOrThrow(COL_ID_MUSIC)));
				}
				tableIsEmpty = c.moveToNext();
			}
			// DELETE ARTIST, GENRE, ALBUM OR PLAYLIST USELESS
			// ARTIST
			ArrayList<Artist> listAr = cursorToArtist(getAllArtist());
			for(i=0;i<listAr.size();i++) {
				Cursor cArtist = getMusicByArtist(listAr.get(i));
				if(!cArtist.moveToFirst()) deleteArtist(listAr.get(i).getId());
				i++;
			}
			// ALBUM
			ArrayList<Album> listAl = cursorToAlbum(getAllAlbum());
			for(i=0;i<listAl.size();i++) {
				Cursor cAlbum = getMusicByAlbum(listAl.get(i));
				if(!cAlbum.moveToFirst()) deleteAlbum(listAl.get(i).getId());
				i++;
			}
			// GENRE
			ArrayList<Genre> listG = cursorToGenre(getAllGenre());
			for(i=0;i<listG.size();i++) {
				Cursor cAlbum = getMusicByGenre(listG.get(i));
				if(!cAlbum.moveToFirst()) deleteGenre(listG.get(i).getId());
				i++;
			}
			// PLAYLIST
			ArrayList<Playlist> listP = cursorToPlaylist(getAllPlaylist());
			for(i=0;i<listP.size();i++) {
				Cursor cAlbum = getMusicByPlaylist(listP.get(i));
				if(!cAlbum.moveToFirst()) deletePlaylist(listP.get(i).getId());
				i++;
			}
			
		}
	}
	
	
	/**
	 * MAJPochette est la méthode qui appelera l'APIAlbumCover
	 * Cette méthode a pour but de parcourir tous les albums et pour ceux qui n'ont pas de pochettes
	 * alors on appelle l'APIAlbumCover.
	 * L'image sous forme de tableau d'octets retournée par l'API est alors stockée dans la base de données et
	 * les pochettes pour ces albums seront alors visibles sur le lecteur. 
	 */
	public void MAJPochette(){
		ArrayList<Album> albumList = new ArrayList<Album>();
		
		Utilities util = new Utilities();
		this.open();
		albumList = this.cursorToAlbum(this.getAllAlbum());
		ArrayList<HashMap<String, String>> musicListView = new ArrayList<HashMap<String,String>>();
		

		for(int i=0;i<albumList.size();i++) {
			Album a = albumList.get(i);
			musicListView.add(util.AlbumToHashMap(a));
			if(a.getAlbumCover() == null){
				Artist ar = this.cursorToArtist(this.getArtist(a.getIdArtist())).get(0);
				Log.v("a", "a " + a.getName().toString());
				Log.v("ar", "ar" + ar.getName().toString());
						
				APIAlbumCover albumCover = new APIAlbumCover();
				byte[] test;
				try {
					test = albumCover.getPochetteAlbum(ar.getName().toString(), a.getName().toString());
					a.setAlbumCover(test);
					this.updateAlbum(a);
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ParserConfigurationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SAXException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (TransformerException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}				
			}
			else{
				//Toast.makeText(getApplicationContext(), a.getAlbumCover().toString(), Toast.LENGTH_SHORT).show();
			}
		}
		this.close();
	}
	
}
